package com.longge;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-04-20 02:37
 */
public class DetectCycle {

    public ListNode detectCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) break;
        }
        if (fast == null || fast.next == null) {
            return null;
        }
        slow = head;
        while (true) {
            if (slow == fast) return slow;
            slow=slow.next;
            fast=fast.next;
        }

    }
}
